import React, { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Input } from './ui/input';
import { Label } from './ui/label';
import { Badge } from './ui/badge';
import { Avatar, AvatarFallback } from './ui/avatar';
import { Progress } from './ui/progress';
import { 
  User, 
  Calendar, 
  Trophy, 
  Edit3, 
  Save, 
  X,
  TrendingUp,
  Target,
  Brain,
  Award,
  BarChart3
} from 'lucide-react';
import { TestResult, UserProfile, Achievement } from '../types';

interface ProfilePageProps {
  userProfile: UserProfile;
  testResults: TestResult[];
  achievements: Achievement[];
  onUpdateProfile: (profile: UserProfile) => void;
}

export function ProfilePage({ userProfile, testResults, achievements, onUpdateProfile }: ProfilePageProps) {
  const [isEditing, setIsEditing] = useState(false);
  const [editForm, setEditForm] = useState({
    name: userProfile.name,
    age: userProfile.age?.toString() || ''
  });

  const handleSave = () => {
    onUpdateProfile({
      ...userProfile,
      name: editForm.name,
      age: editForm.age ? parseInt(editForm.age) : undefined
    });
    setIsEditing(false);
  };

  const handleCancel = () => {
    setEditForm({
      name: userProfile.name,
      age: userProfile.age?.toString() || ''
    });
    setIsEditing(false);
  };

  const getTestHistory = () => {
    return testResults
      .sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime())
      .slice(0, 10);
  };

  const getPerformanceStats = () => {
    if (testResults.length === 0) return null;

    const scores = testResults.map(r => r.score);
    const bestScore = Math.max(...scores);
    const recentScores = testResults.slice(-5).map(r => r.score);
    const recentAverage = recentScores.reduce((sum, score) => sum + score, 0) / recentScores.length;
    
    const testsByType = testResults.reduce((acc, result) => {
      if (!acc[result.testType]) {
        acc[result.testType] = [];
      }
      acc[result.testType].push(result.score);
      return acc;
    }, {} as Record<string, number[]>);

    const bestTestType = Object.entries(testsByType).reduce((best, [testType, scores]) => {
      const avg = scores.reduce((sum, score) => sum + score, 0) / scores.length;
      return avg > best.average ? { testType, average: avg } : best;
    }, { testType: '', average: 0 });

    return {
      bestScore,
      recentAverage: Math.round(recentAverage),
      bestTestType: bestTestType.testType,
      totalTests: testResults.length,
      uniqueTests: Object.keys(testsByType).length
    };
  };

  const getProgressToNextLevel = () => {
    const testsForNextLevel = userProfile.level * 3;
    const progress = (userProfile.totalTests / testsForNextLevel) * 100;
    return Math.min(100, progress);
  };

  const getMostRecentAchievements = () => {
    return achievements
      .filter(a => a.unlocked)
      .sort((a, b) => (b.unlockedDate?.getTime() || 0) - (a.unlockedDate?.getTime() || 0))
      .slice(0, 6);
  };

  const performanceStats = getPerformanceStats();
  const testHistory = getTestHistory();
  const recentAchievements = getMostRecentAchievements();
  const progressToNextLevel = getProgressToNextLevel();

  return (
    <div className="max-w-4xl mx-auto space-y-8">
      {/* Profile Header */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="flex items-center gap-2">
              <User className="w-5 h-5" />
              个人档案
            </CardTitle>
            {!isEditing ? (
              <Button variant="outline" size="sm" onClick={() => setIsEditing(true)}>
                <Edit3 className="w-4 h-4 mr-2" />
                编辑
              </Button>
            ) : (
              <div className="flex gap-2">
                <Button variant="outline" size="sm" onClick={handleCancel}>
                  <X className="w-4 h-4 mr-2" />
                  取消
                </Button>
                <Button size="sm" onClick={handleSave}>
                  <Save className="w-4 h-4 mr-2" />
                  保存
                </Button>
              </div>
            )}
          </div>
        </CardHeader>
        <CardContent>
          <div className="flex items-start gap-6">
            <Avatar className="w-24 h-24">
              <AvatarFallback className="text-2xl">
                {userProfile.name.charAt(0).toUpperCase()}
              </AvatarFallback>
            </Avatar>
            
            <div className="flex-1 space-y-4">
              {!isEditing ? (
                <div>
                  <h2 className="text-2xl font-bold">{userProfile.name}</h2>
                  {userProfile.age && (
                    <p className="text-muted-foreground">{userProfile.age} 岁</p>
                  )}
                </div>
              ) : (
                <div className="space-y-4 max-w-md">
                  <div className="space-y-2">
                    <Label htmlFor="name">姓名</Label>
                    <Input
                      id="name"
                      value={editForm.name}
                      onChange={(e) => setEditForm(prev => ({ ...prev, name: e.target.value }))}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label htmlFor="age">年龄（可选）</Label>
                    <Input
                      id="age"
                      type="number"
                      value={editForm.age}
                      onChange={(e) => setEditForm(prev => ({ ...prev, age: e.target.value }))}
                    />
                  </div>
                </div>
              )}
              
              <div className="flex items-center gap-4">
                <Badge variant="secondary" className="flex items-center gap-1">
                  <Trophy className="w-3 h-3" />
                  等级 {userProfile.level}
                </Badge>
                <Badge variant="outline" className="flex items-center gap-1">
                  <Calendar className="w-3 h-3" />
                  加入于 {userProfile.joinDate.toLocaleDateString('zh-CN')}
                </Badge>
              </div>
              
              <div className="space-y-2">
                <div className="flex justify-between text-sm">
                  <span>升级进度</span>
                  <span>{userProfile.totalTests}/{userProfile.level * 3} 测试</span>
                </div>
                <Progress value={progressToNextLevel} className="h-2" />
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Left Column - Stats */}
        <div className="lg:col-span-2 space-y-6">
          {/* Performance Overview */}
          {performanceStats && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <BarChart3 className="w-5 h-5" />
                  表现概览
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                  <div className="text-center p-4 bg-blue-50 dark:bg-blue-950 rounded-lg">
                    <div className="text-2xl font-bold text-blue-600">{performanceStats.totalTests}</div>
                    <div className="text-sm text-muted-foreground">总测试数</div>
                  </div>
                  <div className="text-center p-4 bg-green-50 dark:bg-green-950 rounded-lg">
                    <div className="text-2xl font-bold text-green-600">{performanceStats.bestScore}</div>
                    <div className="text-sm text-muted-foreground">最高分</div>
                  </div>
                  <div className="text-center p-4 bg-purple-50 dark:bg-purple-950 rounded-lg">
                    <div className="text-2xl font-bold text-purple-600">{performanceStats.recentAverage}</div>
                    <div className="text-sm text-muted-foreground">近期平均</div>
                  </div>
                  <div className="text-center p-4 bg-orange-50 dark:bg-orange-950 rounded-lg">
                    <div className="text-2xl font-bold text-orange-600">{performanceStats.uniqueTests}</div>
                    <div className="text-sm text-muted-foreground">测试类型</div>
                  </div>
                </div>
                
                {performanceStats.bestTestType && (
                  <div className="mt-4 p-3 bg-muted rounded-lg">
                    <div className="flex items-center gap-2">
                      <Target className="w-4 h-4 text-primary" />
                      <span className="text-sm">
                        您在 <strong>{performanceStats.bestTestType}</strong> 中表现最佳
                      </span>
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>
          )}

          {/* Test History */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <TrendingUp className="w-5 h-5" />
                测试历史
              </CardTitle>
            </CardHeader>
            <CardContent>
              {testHistory.length > 0 ? (
                <div className="space-y-3">
                  {testHistory.map((result, index) => (
                    <div key={index} className="flex items-center justify-between p-4 border rounded-lg hover:bg-muted/50 transition-colors">
                      <div className="flex-1">
                        <h4 className="font-medium">{result.testType}</h4>
                        <p className="text-sm text-muted-foreground">
                          {result.timestamp.toLocaleDateString('zh-CN', {
                            year: 'numeric',
                            month: 'short',
                            day: 'numeric',
                            hour: '2-digit',
                            minute: '2-digit'
                          })}
                        </p>
                        <p className="text-xs text-muted-foreground mt-1">{result.details}</p>
                      </div>
                      <div className="text-right">
                        <div className="text-xl font-bold text-primary">{result.score}</div>
                        {result.percentile && (
                          <div className="text-xs text-muted-foreground">
                            第{Math.round(result.percentile)}百分位
                          </div>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <div className="text-center py-8 text-muted-foreground">
                  <BarChart3 className="w-12 h-12 mx-auto mb-4 opacity-50" />
                  <p>还没有测试记录</p>
                </div>
              )}
            </CardContent>
          </Card>
        </div>

        {/* Right Column */}
        <div className="space-y-6">
          {/* Recent Achievements */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Award className="w-5 h-5" />
                成就展示
              </CardTitle>
            </CardHeader>
            <CardContent>
              {recentAchievements.length > 0 ? (
                <div className="space-y-3">
                  {recentAchievements.map((achievement) => {
                    const Icon = achievement.icon;
                    return (
                      <div key={achievement.id} className="flex items-center gap-3 p-3 bg-yellow-50 dark:bg-yellow-950 rounded-lg">
                        <Icon className="w-6 h-6 text-yellow-500" />
                        <div className="flex-1">
                          <h4 className="font-medium">{achievement.name}</h4>
                          <p className="text-sm text-muted-foreground">{achievement.description}</p>
                          {achievement.unlockedDate && (
                            <p className="text-xs text-muted-foreground mt-1">
                              {achievement.unlockedDate.toLocaleDateString('zh-CN')}
                            </p>
                          )}
                        </div>
                      </div>
                    );
                  })}
                </div>
              ) : (
                <div className="text-center py-6 text-muted-foreground">
                  <Trophy className="w-8 h-8 mx-auto mb-2 opacity-50" />
                  <p className="text-sm">完成测试来解锁成就</p>
                </div>
              )}
            </CardContent>
          </Card>

          {/* User Statistics Summary */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Brain className="w-5 h-5" />
                个人统计
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div className="grid grid-cols-2 gap-3 text-center">
                <div className="p-3 bg-blue-50 dark:bg-blue-950 rounded-lg">
                  <div className="text-lg font-bold text-blue-600">{userProfile.level}</div>
                  <div className="text-xs text-muted-foreground">当前等级</div>
                </div>
                <div className="p-3 bg-green-50 dark:bg-green-950 rounded-lg">
                  <div className="text-lg font-bold text-green-600">{userProfile.averageScore}</div>
                  <div className="text-xs text-muted-foreground">平均分数</div>
                </div>
                <div className="p-3 bg-purple-50 dark:bg-purple-950 rounded-lg">
                  <div className="text-lg font-bold text-purple-600">{userProfile.totalTests}</div>
                  <div className="text-xs text-muted-foreground">总测试数</div>
                </div>
                <div className="p-3 bg-orange-50 dark:bg-orange-950 rounded-lg">
                  <div className="text-lg font-bold text-orange-600">{recentAchievements.length}</div>
                  <div className="text-xs text-muted-foreground">解锁成就</div>
                </div>
              </div>
              
              <div className="p-3 bg-muted rounded-lg">
                <div className="text-sm text-muted-foreground mb-1">
                  加入时间: {Math.floor((Date.now() - userProfile.joinDate.getTime()) / (1000 * 60 * 60 * 24))} 天前
                </div>
                <div className="text-sm text-muted-foreground">
                  距离下一级别还需: {Math.max(0, userProfile.level * 3 - userProfile.totalTests)} 个测试
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}